import com.fasterxml.jackson.databind.ObjectMapper;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: WHY
 * Date: 2023-06-06
 * Time: 17:56
 */
class Message{
    //属性必须设置public
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    //解析要使用json的这个类
    private ObjectMapper objectMapper=new ObjectMapper();
    //消息存起来
    //private List<Message> messageList=new ArrayList<>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法来处理"获取所有留言信息"
        //需要返回json 字符串数组,jackson直接帮我们处理好了格式
        List<Message> messageList=load();
        String respString =objectMapper.writeValueAsString(messageList);
        //通过这一步就把message对象变成了json数组
        resp.setContentType("application/json; charset=utf8");
        resp.getWriter().write(respString);
    }




    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //通过这个方法来处理"提交的新消息"
        //解析json格式的body为Message对象
        //第一个参数是获取请求的body ,第二个参数写的是要转成啥样的对象
       Message message=    objectMapper.readValue(req.getInputStream(),Message.class);
       save(message);
        System.out.println("消息提交成功 message="+ message);
        //响应body为空,不需要额外处理,默认为200

    }

    //这个方法用来往数据库存一条记录
    private void save(Message message) {
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/why?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1111");
        try{
            Connection connection=dataSource.getConnection();
            String sql="insert into message values(?,?,?)";//占位符
            //设置占位符内容
            PreparedStatement statement=connection.prepareStatement(sql);
            statement.setString(1,message.from);
            statement.setString(2,message.to);
            statement.setString(3,message.message);
            //执行sql
            statement.executeUpdate();
            statement.close();
            connection.close();
        }catch(SQLException  e){
            e.printStackTrace();
        }


    }
    //这个方法用来从数据库查询所有记录
    private List<Message> load() {
        List<Message> messageList=new ArrayList<>();
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/why?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1111");
        try{
            Connection connection=dataSource.getConnection();
            String sql="select *from message";//占位符
            //设置占位符内容
            PreparedStatement statement=connection.prepareStatement(sql);
            //执行sql
            ResultSet resultSet= statement.executeQuery();
            //遍历结果集
            while(resultSet.next()){
                Message message=new Message();
                message.from=resultSet.getString("from");
                message.to=resultSet.getString("to");

                message.message=resultSet.getString("message");
                messageList.add(message);
            }

            resultSet.close();
            statement.close();
            connection.close();
        }catch(SQLException  e){
            e.printStackTrace();
        }
        return messageList;

    }
}
